#include <memory>
#include "TcpServer.hpp"

Respense calculator(const Request& rep)
{
    Respense resp(0,0);
    switch(rep._op)
    {
    case '+':
        resp._result = rep._x + rep._y;
        break;
    case '-':
        resp._result = rep._x - rep._y;
        break;
    case '*':
        resp._result = rep._x * rep._y;
        break;
    case '/':
        if (rep._y == 0)    resp._code = 1;
        else resp._result = rep._x / rep._y;
        break;
    case '%':
        if (rep._y == 0)    resp._code = 2;
        else resp._result = rep._x % rep._y;
        break;
    default:
        resp._code = 3;
        break;
    }

    return resp;
}


void NetCal(Connection* conn, std::string& request)
{
    logMessage(DEBUG, "Net been called, get request: %s", request.c_str());

    // 1.序列化
    Request req;
    if (!req.Deserialize(request)) return ;

    // 2.业务处理
    Respense resp = calculator(req);

    // 3.序列化,构建应答
    std::string sendstr = resp.Serialize();
    sendstr = EnCode(sendstr);

    // 4.交给服务器,进行发送
    conn->_outbuffer += sendstr;

    // 5.让底层TcpServer赶紧发送
    conn->_tsvr->EnableReadWrite(conn, true, true);
    std::cout << "#############################" << std::endl;
}

int main()
{
    std::unique_ptr<TcpServer> src(new TcpServer());
    src->start(NetCal);
    return 0;
}